package com.sea.base.json.typeAdapter

import com.google.gson.JsonArray
import com.google.gson.JsonNull
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
import com.google.gson.TypeAdapter
import com.google.gson.internal.Streams
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter

class DefStringTypeAdapter : TypeAdapter<String>() {
    override fun write(out: JsonWriter, value: String?) {
        out.value(value)
    }

    override fun read(inReader: JsonReader?): String? {
        return when (val je = Streams.parse(inReader)) {
            is JsonNull -> {
                null
            }

            is JsonPrimitive -> {
                je.asString
            }

            is JsonObject, is JsonArray -> {
                je.toString()
            }

            else -> {
                throwE(inReader, je, "String")
            }
        }
    }
}